package com.sankuai.inf.leaf.server.controller;



import com.bat.BaseController;
import com.bat.util.R;
import com.sankuai.inf.leaf.segment.model.User;
import com.sankuai.inf.leaf.server.config.LocalMvcConfiguration;
import com.sankuai.inf.leaf.server.service.LoginService;
import com.sankuai.inf.leaf.server.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author final
 * @description
 * @date 2019-09-06 16:38
 */

@RestController
@RequestMapping("/api")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @GetMapping("/user")
    public R<User> getUserByUserName(String username) {
        return this.s(userService.getUserByUserName(username));
    }

    @GetMapping("/users")
    public R<List<User>> listUser() {
        return this.s(userService.listUser());
    }

    @PostMapping("/user")
    public R addUser(@RequestBody User user) throws Exception {
        if(ObjectUtils.isEmpty(user)){
            //throw new Exception(100505, "用户名或密码不能为空");
            throw new Exception("用户名或密码不能为空");
        }
        userService.addUser(user.getUsername(),user.getPassword());
        return this.s();
    }
    @PutMapping("/user")
    public R updateUser(@RequestBody User user) throws Exception {
        userService.updateUser(user);
        return this.s();
    }

    @GetMapping("/page")
    public R userPage(HttpSession session) {
        Object username = session.getAttribute(LocalMvcConfiguration.SESSION_KEY);
        if(!ObjectUtils.isEmpty(username)&& StringUtils.equals(username.toString(), LoginService.ADMIN_ROLE)){
            return this.s("home/user/list.html");
        }
        return this.s();
    }
}

